import 'package:flutter/material.dart';

class CustomSearchBar extends StatefulWidget {
  final ValueChanged<String> onInputComplete;
  final double fHeight;

  const CustomSearchBar(
      {Key? key, required this.onInputComplete, this.fHeight = 50})
      : super(key: key);

  @override
  _CustomSearchBarState createState() => _CustomSearchBarState();
}

class _CustomSearchBarState extends State<CustomSearchBar> {
  late TextEditingController _textEditingController;
  final FocusNode _focusNode = FocusNode();

  bool _showClearButton = false;

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController();
    _textEditingController.addListener(() {
      setState(() {
        _showClearButton = _textEditingController.text.isNotEmpty;
      });
    });

    _focusNode.addListener(_onFocusChanged);
  }

  void _onFocusChanged() {
    if (!_focusNode.hasFocus) {
      widget.onInputComplete(_textEditingController.text);
    }
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    _focusNode.removeListener(_onFocusChanged);
    _focusNode.dispose();
    super.dispose();
  }

  void _clearText() {
    _textEditingController.clear();
    widget.onInputComplete(_textEditingController.text);
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.fHeight,
      child: TextField(
        controller: _textEditingController,
        focusNode: _focusNode,
        decoration: InputDecoration(
          hintText: 'Search',
          prefixIcon: const Icon(Icons.search, color: Colors.grey),
          suffixIcon: _showClearButton
              ? IconButton(
                  onPressed: _clearText,
                  icon: const Icon(Icons.clear, color: Colors.grey),
                )
              : null,
          contentPadding: const EdgeInsets.all(0),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(0.5 * widget.fHeight),
            borderSide: const BorderSide(color: Colors.grey),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(0.5 * widget.fHeight),
            borderSide: const BorderSide(color: Colors.grey),
          ),
        ),
      ),
    );
  }
}
